package com.gaussian.property.admin.module.system.controller.system;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.gaussian.property.admin.module.system.service.SysPermissionService;
import com.songqi.common.core.domain.R;
import com.songqi.common.core.domain.page.PageDataInfo;
import com.songqi.common.core.utils.ServletUtils;
import com.songqi.common.core.utils.StringUtils;
import com.songqi.common.log.annotation.Log;
import com.gaussian.property.module.system.enums.BusinessType;
import com.songqi.common.security.model.LoginUser;
import com.songqi.common.security.service.TokenService;
import com.songqi.common.security.utils.SecurityUtils;
import com.songqi.common.web.request.controller.BaseController;
import com.gaussian.property.module.system.domain.UserConstants;
import com.gaussian.property.module.system.entity.SysRole;
import com.gaussian.property.module.system.entity.SysUser;
import com.gaussian.property.module.system.service.ISysRoleService;
import com.gaussian.property.module.system.service.ISysUserService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 角色信息
 *
 * @author songqi(13776346982)
 */
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController
{
    @Resource
    private ISysRoleService roleService;

    @Resource
    private TokenService tokenService;

    @Resource
    private SysPermissionService permissionService;

    @Resource
    private ISysUserService userService;

    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/list")
    public R<PageDataInfo> list(SysRole role)
    {
        startPage();
        List<SysRole> list = roleService.selectRoleList(role);
        return getDataTable(list);
    }

    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:role:export')")
    @GetMapping("/export")
    public R export(SysRole role)
    {
        List<SysRole> list = roleService.selectRoleList(role);

        Workbook workBook = ExcelExportUtil.exportExcel(new ExportParams(), SysRole.class, list);
        //TODO: 下载
        return R.success();
    }

    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public R getInfo(@PathVariable Long roleId)
    {
        return R.success(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated @RequestBody SysRole role)
    {
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            //角色名称已存在
            return R.error("role.name.has.already.exist");
        }
        else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            //角色权限已存在
            return R.error("role.permission.has.already.exist");
        }
        role.setCreateBy(SecurityUtils.getUsername());
        return toAjax(roleService.insertRole(role));

    }

    /**
     * 修改保存角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated @RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            //角色名称已存在
            return R.error("role.name.has.already.exist");
        }
        else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            //角色权限已存在
            return R.error("role.permission.has.already.exist");
        }
        role.setUpdateBy(SecurityUtils.getUsername());

        if (roleService.updateRole(role) > 0)
        {
            // 更新缓存用户权限
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            if (StringUtils.isNotNull(loginUser.getTokenUser()) && !((SysUser)loginUser.getTokenUser()).isAdmin())
            {
                loginUser.setPermissions(permissionService.getMenuPermission((SysUser) loginUser.getTokenUser()));
                loginUser.setTokenUser(userService.selectUserByUserName(((SysUser) loginUser.getTokenUser()).getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return success();
        }
        return error();
    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public R dataScope(@RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        return toAjax(roleService.authDataScope(role));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public R changeStatus(@RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        role.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(roleService.updateRoleStatus(role));
    }

    /**
     * 删除角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public R remove(@PathVariable Long[] roleIds)
    {
        return toAjax(roleService.deleteRoleByIds(roleIds));
    }

    /**
     * 获取角色选择框列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/optionselect")
    public R optionSelect()
    {
        return R.success(roleService.selectRoleAll());
    }
}
